//
//  Date+Ext.swift
//  WBSwift
//
//  Created by 贺瑞 on 2017/8/4.
//  Copyright © 2017年 herui. All rights reserved.
//

import Foundation

extension Date {
    /**
     例：将字符串 Tue May 31 17:46:55 +0800 2011 转为Date对象
     Date.date(str:"Tue May 31 17:46:55 +0800 2011", format:"EEE MM dd HH:mm:ss Z yyyy")
     EEE 星期
     Z  时区
     */
    static func date(str:String?, format:String) -> Date? {
        guard let str = str else {
            return nil
        }
        let fmt = DateFormatter()
        fmt.locale = Locale(identifier: "en")
        fmt.dateFormat = format;
        return fmt.date(from: str)
    }
    
    /**
     刚刚
     60分钟前
     12小时前
     昨天
     月-日 时:分
     年-月-日  时:分
     */
    func convertToTimelineString() -> String {
        
        let now = Date().timeIntervalSince1970
        let interval = self.timeIntervalSince1970
        
        if(interval > now - 60){
            return "刚刚"
        }
        
        if(interval > now - (60 * 60)){
            let m = Int((now - interval) / 60)
            return "\(m)分钟前"
        }
        
        if(interval > now - (60 * 60 * 12)){
            let h = Int((now - interval) / 60 / 60)
            return "\(h)小时前"
        }
        
        if(NSCalendar.current.isDateInYesterday(self)){
            return convertWithFmt(format: "昨天 HH:mm")
        }
        
        if(NSCalendar.current.component(.year, from: self) < 1){
            return convertWithFmt(format: "MM-dd HH:mm")
        }
        
        return convertWithFmt(format: "yyyy-MM-dd HH:mm")
    }
    
    func convertWithFmt(format : String) -> String {
        let fmt = DateFormatter()
        fmt.locale = Locale.current
        fmt.dateFormat = format;
        return fmt.string(from: self)
    }
    
}
